package benchmarks.tpch.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class DBtool {
    public static void prepareTBL(double scale) {
        class EXE {
            private void dgen(String scale) throws IOException {
                File file = new File("dataset" + File.separator + "dgen.sh");
//                Process pr = runtime.exec(new String[]{"/bin/sh" , file.getPath()});
                ProcessBuilder pb = new ProcessBuilder("bash", file.getAbsolutePath(), scale);
                Process p = pb.start();
                BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null)
                {
                    System.out.println(line);
                }
            }
        }
        String dbPath = getDBpath(scale);
        File folder = new File(dbPath);
        if (folder.exists()) {
            System.out.println("use existed data of " + folder.getPath());
            return;
        }
        try {
            String scaleStr = getScaleStr(scale);
            System.out.println("generate data with scale of " + scaleStr);
            new EXE().dgen(scaleStr);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDBpath(double scale) {
        return "dataset" + File.separator + "tpch" + getScaleStr(scale);
    }

    public static String getScaleStr(double scale) {
        String scaleStr;
        if(scale == (long) scale)
            scaleStr = String.format("%d",(long)scale);
        else
            scaleStr = String.format("%s",scale);
        return scaleStr;
    }
}
